(function ($) {
    $.fn.yqSvrAdDns = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqSvrAdDns.methods[opts](this, param);
        }

        var $this = this;
        var opt = $.extend({}, $.fn.yqSvrAdDns.defaults, opts);

        if ($this.data("yqtype") == "yqSvrAdDns") {
            var $uniqueID = $this.attr("ID");
            destroy($this);
            $this = $("#" + $uniqueID);
        }
        else {
            var $uniqueID = $this.attr("ID");
            if ($uniqueID === undefined) {
                $uniqueID = $.getUniqueID();
                $this.attr("ID", $uniqueID);
            }
        }

        if (opt.width === undefined && $this.width() > 0) {
            opt.width = $this.width();
        }
        else if (typeof opt.width != "undefined") {
            $this.width(opt.width);
        }

        //转换编辑尺寸

        //变量信息
        $this.data("svraddns_opt", opt);
        $this.data("yqtype", "yqSvrAdDns");

        init_ui($this);
    };

    $.fn.yqSvrAdDns.defaults = {
        ajaxUrl: "/_svradmin.html",
        isEdit: true,
        beforeBindingTitle: function (callback) {
            callback();
        }, //标题绑定前
        afterBindingTitle: function () { },   //标题绑定后
    };

    $.fn.yqSvrAdDns.methods = {
        options: function (jq) {
            return options(jq);
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, params) {
            resize(jq, params);
        },
        clear: function (jq, data) {
            setRows(jq, []);
        },
        setRows: function (jq, rows) {
            setRows($(jq[0]), rows);
        },
        getRows: function (jq) {
            return getRows($(jq[0]));
        },
        isEdit: function (jq, tf) {
            isEdit($(jq[0]), tf);
        }
    };

    function options($object) {
        return $object.data("svraddns_opt");
    }

    function isEdit($object, tf) {
        var opt = options($object);
        if (tf === undefined) {
            tf = opt.isEdit;
        } else {
            opt.isEdit = tf;
        }
        opt.$edit_main.yqTableEdit("isEdit", tf);
        opt.$edit_set.yqTableEdit("isEdit", tf);
        opt.$dns_save.linkbutton(tf ? "enable" : "disable");
        opt.$dns_port.numberspinner(tf ? "enable" : "disable");
    }

    function destroy($object) {

    }

    function resize($object, params) {
        var opt = options($object);
        if (!(params === undefined)) {
            if (!(params.width === undefined)) {
                opt.width = params.width;
            }
            if (!(params.height === undefined)) {
                opt.height = params.height;
            }
        }

        var l_w = 340;
        var h_ = opt.height - 43;
        if (h_ < 300) {
            h_ = 300;
        }

        opt.$edit_main.yqTableEdit("resize", {
            width: l_w,
            height: h_,
        });

        var r_w = opt.width - l_w - 3;
        if (r_w < 340) {
            r_w = 340;
        }
        opt.$edit_set.yqTableEdit("resize", {
            width: r_w,
            height: h_,
        });
    }

    function page_load($object) {
        var opt = options($object);

        resize($object);
        opt.afterBindingTitle();

        json_get($object, function (data) {
            opt.$dns_port.numberspinner("setValue", data.addr === undefined ? 53 : data.addr);
            opt.$edit_main.yqTableEdit("setRows", data.data === undefined ? [] : data.data);
            opt.$edit_set.yqTableEdit("setRows", []);

            isEdit($object);

            status($object);
            opt.$dns_save.linkbutton("enable");
        });
    }

    function init_ui($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("ID");
        var h_ = `
    <table style="width: 100%;">
        <tr>
            <td style="padding:4px;">
                <input class="dns_status"/>
                <a class="dns_save"></a>
            </td>
            <td style="padding:4px;text-align:right;">
                <span>端口号：</span>
                <input class="dns_port"/>
            </td>
        </tr>
        <tr>
            <td style="padding:0 3px 0 0;width:340px;">
                <table class="edit_main" style="width:340px;height:300px;"></table>
            </td>
            <td style="padding:0;">
                <table class="edit_set" style="width:500px;height:300px;"></table>
            </td>
        </tr>
    </table>
                `;

        $object.html(h_);

        opt.$btn_status = $object.find(".dns_status");
        opt.$dns_save = $object.find(".dns_save");
        opt.$edit_main = $object.find(".edit_main");
        opt.$edit_set = $object.find(".edit_set");
        opt.$dns_port = $object.find(".dns_port");

        opt.$btn_status.switchbutton({
            width: 95,
            height: 35,
            handleWidth: 50,
            checked: false,
            handleText: "DNS",
            onText: '开启',
            offText: '关闭',
            disabled: true,
        });

        opt.$dns_save.linkbutton({
            width: 90,
            height: 35,
            text: "保存",
            iconCls: "yqwin-btn-icon fa fa-floppy-o",
            disabled: true,
            onClick: function () {
                opt.$edit_set.yqTableEdit("endEditing");
                var rows = opt.$edit_main.yqTableEdit("getRows");
                opt.$edit_main.yqTableEdit("endEditing");
                var addr = opt.$dns_port.numberspinner("getValue");
                if (addr === undefined || addr < 1 || addr > 65535) {
                    $.yqMessager("端口号错误！");
                    return;
                }
                var data = {
                    "addr": parseInt(addr),
                    "data": rows,
                }
                console.log(data);
                json_set($object, JSON.stringify(data, null, 3));
            }
        });

        opt.$dns_port.numberspinner({
            width: 60,
            height: 35,
            disabled: true,
            value: 53,
        })

        init_ui_main($object);
    }

    function init_ui_main($object) {
        var opt = options($object);

        var titles = [{
            "name": "domain",
            "ui_title": "domain",
            "ui_type": 2,
            "ui_width": 160,
            "ui_visible": true,
            "ui_readonly": false,
            "ui_mask": {
                "blank": false,
            }
        }, {
            "name": "tag",
            "ui_title": "tag",
            "ui_type": 5,
            "ui_width": 130,
            "ui_visible": true,
            "ui_readonly": false,
            "ui_mask": {
                "editModeW": 400,
                "editModeH": 300,
                "default": "base",
                "types": [
                    "base"
                ]
            }
        }, {
            "name": "sub",
            "ui_title": "sub",
            "ui_type": 15,
            "ui_width": 130,
            "ui_visible": false,
            "ui_readonly": false,
            "ui_mask": {
                "editModeW": 450,
                "editModeH": 450,
                "editType": 0,
                "modelNo": -1,
                "panelWidth": 500,
                "panelHeight": 400,
                "param": {
                    "titles": [],
                    "model": []
                },
                "rows": []
            }
        }];

        opt.$edit_main.yqTableEdit({
            ajaxUrl: "",
            titles: titles,
            rows: [],
            isEdit: false,
            isAdd: true,
            isDel: true,
            beforBindingTitle: function (titles, callback) {
                callback(titles);
            }, //标题绑定前
            afterBindingTitle: function () {
                init_ui_set($object);
            }, //标题绑定后       
            endEditing: function (index, row) {
            },
            onClickRow: function (index, row) {
                var sub_rows = row.sub;
                if (sub_rows === undefined) {
                    sub_rows = [];
                }
                opt.$edit_set.yqTableEdit("setRows", sub_rows);
            },
            // endEditing: function (index, row) {
            //     var rows = opt.$edit_set.yqTableEdit("getRows");
            //     row.sub = rows;
            // },
            beforeAdd: function (rows, row, callback) {
                opt.$edit_set.yqTableEdit("setRows", []);
                callback(row);
            },
        });
    }

    function init_ui_set($object) {
        var opt = options($object);

        var titles = [{
            "name": "dnstype",
            "ui_title": "type",
            "ui_type": 6,
            "ui_width": 100,
            "ui_visible": true,
            "ui_readonly": false,
            "ui_mask": {
                "type": "string",
                "lists": [
                    {
                        "no": "A",
                        "name": "A"
                    },
                    {
                        "no": "AAAA",
                        "name": "AAAA"
                    },
                    {
                        "no": "MX",
                        "name": "MX"
                    },
                    {
                        "no": "TXT",
                        "name": "TXT"
                    }
                ],
                "default": 1,
                "blank": false,
                onChange: function (target, value) {
                    upp_value_change(opt)
                    if (value === "") {
                        return;
                    }
                    upp_value_type(opt, value);
                },
            },

        }, {
            "name": "name",
            "ui_title": "name",
            "ui_type": 2,
            "ui_width": 80,
            "ui_visible": true,
            "ui_readonly": false,
            "ui_mask": {
                "blank": false,
                onChange: function (target, value) {
                    upp_value_change(opt)
                },
            }
        }, {
            "name": "value",
            "ui_title": "value",
            "ui_type": 20,
            "ui_width": 240,
            "ui_visible": true,
            "ui_readonly": false,
            "ui_mask": {
                "blank": false,
                "ui_type": 2,
                "separator": "`",
                "editModeW": 280,
                "editModeH": 200,
                "isMove": true,
                "beforeEditShow": function (edit_type, options, callback) {
                    var type = opt.$edit_set.yqTableEdit("getField", "dnstype");
                    console.log(edit_type, type);
                    console.log(options);
                    if (type === "A" || type === "AAAA") {
                        edit_type = "yqTextRichBox";
                        options = {
                            value: options.value,
                            blank: false,
                            min: 0,
                            max: 10000,
                            types: ["base"],
                            type: "base",
                            isEdit: options.isEdit,   //可编辑
                            editModeW: options.editModeW, //模态编辑器宽度 格式为 800（数字）
                            editModeH: options.editModeH, //模态编辑器高度 格式为 600（数字）
                        };
                        callback(true, edit_type, options);
                    } else if (type === "MX" || type === "TXT") {
                        callback(true, edit_type, options);
                    } else {
                        callback(false, edit_type, options);
                    }
                }, //弹出框显示前
                afterChange: function (value) {
                    upp_value_change(opt);
                },
            }
        }, {
            "name": "tag",
            "ui_title": "tag",
            "ui_type": 5,
            "ui_width": 230,
            "ui_visible": true,
            "ui_readonly": false,
            "ui_mask": {
                "editModeW": 350,
                "editModeH": 200,
                "default": "base",
                "types": [
                    "base"
                ],
                onChange: function (target, value) {
                    upp_value_change(opt)
                },
            }
        }];

        opt.$edit_set.yqTableEdit({
            ajaxUrl: "",
            titles: titles,
            rows: [],
            isEdit: false,
            isAdd: true,
            isDel: true,
            beforBindingTitle: function (titles, callback) {
                callback(titles);
            }, //标题绑定前
            afterBindingTitle: function () {
                page_load($object);
            }, //标题绑定后  
            beginEdit: function (index, row) {
                var dnstype = opt.$edit_set.yqTableEdit("getField", "dnstype");
                upp_value_type(opt, dnstype);
            },
            endEditing: function (index, row) {   //ok.....
            },
            beforeAdd: function (rows, row, callback) {
                callback(row);
            },
        });
    }
    function upp_value_change(opt) {
        var rows = opt.$edit_set.yqTableEdit("getRows_2");
        opt.$edit_main.yqTableEdit("setField", {
            name: "sub",
            value: rows
        });
        // console.log("afterChange", value, rows);
    }

    function upp_value_type(opt, dnstype) {
        var $obj = opt.$edit_set.yqTableEdit("getFieldObj", "value");
        if ($obj === null) {
            return;
        }
        $obj.yqTextCSV("showEdit", !(dnstype === "A" || dnstype === "AAAA"));
    }

    function start($object) {
        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "dns:start");
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    console.log(res);
                    if (res.error == 0) {
                        status($object);
                    } else {
                        disable($object);
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                disable($object);
            }
        });
    }

    function stop($object) {
        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "dns:stop");
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    console.log(res);
                    if (res.error == 0) {
                        status($object);
                    } else {
                        disable($object);
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                disable($object);
            }
        });
    }

    function status($object) {
        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "dns:status");
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    console.log(res);
                    if (res.error == 0) {
                        opt.$btn_status.switchbutton(res.status ? "check" : "uncheck");
                        opt.$btn_status.switchbutton("enable");
                        var status_opt = opt.$btn_status.switchbutton("options");
                        status_opt.onChange = function (checked) {
                            status_opt.onChange = function (checked) { };
                            if (checked) {
                                start($object);
                            } else {
                                stop($object);
                            }
                        };
                    } else {
                        disable($object)
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                disable($object)
            }
        });
    }

    function json_get($object, callback) {
        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "dns:get");
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    console.log(res);
                    if (res.error == 0) {
                        callback(res.dns);
                    } else {
                        callback({});
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                callback({});
            }
        });
    }

    function json_set($object, dns_json) {
        var opt = options($object);

        var formData = new FormData();
        formData.append("action", "dns:set");
        formData.append("dns", dns_json);
        $.ajax({
            type: 'POST',
            url: opt.ajaxUrl,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (res) {
                if ($.yqDataErrCheck(res)) {
                    console.log(res);
                    if (res.error == 0) {
                        $.yqMessager("success", "执行成功。");
                    } else {
                        $.yqMessager("error", res.info + "[" + res.error + "]");
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest.responseText);
                $.yqMessager("error", XMLHttpRequest.responseText);
            }
        });
    }

    function disable($object) {
        var opt = options($object);
        opt.$btn_status.switchbutton("uncheck");
        opt.$btn_status.switchbutton("disable");
    }

    function setRows($object, rows) {
        var opt = options($object);
        opt.$edit_main.yqTableEdit("setRows", rows);
    }

    function getRows($object) {
        var opt = options($object);
        return opt.$edit_main.yqTableEdit("getRows");
    }
})(jQuery);